<?php

namespace app\helpers;

use Yii;
use app\models\RedisStore;

/**
 * 参数
 *
 * $params['data'] = array(        //邮件数据
 *     'demo_key' => $demo_value,
 * );
 * $params['sub'] = $subject;      //邮件标题
 * $params['to'] = $email;         //收件人邮箱
 * $params['view'] = 'feedback';   //邮件模版
 * $params['async'] = true;        //是否异步发送，是：ture；否：false
 */

class EmailHelper
{
    public $layout = '@app/mail/layouts/html';
    const FROM_EMAIL = 'yii2smtp@sohu.com'; //发件人邮箱
    const FROM_USER = 'system'; //发件人名称

    /**
     * 发送邮件
     *
     * @param array $params
     *        string ['to'] 收件人
     *        string ['bcc'] 密送
     *        string ['cc'] 抄送
     *        string ['sub'] 主题
     *        bool   ['async'] 是否异步
     *        string ['view'] 视图路径
     *        array  ['data'] 视图数据
     *        string ['text'] 纯文本邮件
     *
     * @return bool
     */
    public static function sendEmail($params)
    {
        // 必填参数
        if (empty($params['to']) || empty($params['sub']) || (!empty($params['data']) && empty($params['view']))) {
            return false;
        }

        if (isset($params['async']) && (true === $params['async'])) { // 异步发送

            unset($params['async']);

            $redis = new RedisStore();
            $listCount = $redis->pushQueue(RedisStore::Q_SYNC_SEND_EMAIL, json_encode($params));

            return $listCount > 0 ? true : false;
        } else { // 即时发送
            // 模板邮件
            if (isset($params['view'])) {
                // 设置布局路径
                Yii::$app->mailer->htmlLayout = Yii::$app->params['mailTmpPath'].'layouts/html';
                if (isset($params['data'])) {
                    $mailer = Yii::$app->mailer->compose(Yii::$app->params['mailTmpPath'] . $params['view'], $params['data']);
                } else {
                    $mailer = Yii::$app->mailer->compose(Yii::$app->params['mailTmpPath'] . $params['view']);
                }
            } else { // 纯文本
                $mailer = Yii::$app->mailer->compose();
            }

            $mailer->setFrom([self::FROM_EMAIL => self::FROM_USER]);
            $mailer->setTo($params['to']);
            $mailer->setSubject($params['sub']);

            //抄送
            if (isset($params['cc'])) {
                $mailer->setCc($params['cc']);
            }

            //密送
            if (isset($params['bcc'])) {
                $mailer->setBcc($params['bcc']);
            }

            // 纯文本
            if (isset($params['text'])) {
                $mailer->setTextBody($params['text']);
            }

            // 验证发送
            if ($mailer->send()) {
                return true;
            }
            return false;
        }
    }
}
